package com.sgb.kjwl.view.ui.activity.self.publish;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.GridLayoutManager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPackersTypeChooiceBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.user.CategoryEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.self.PackersPublishEvent;
import com.sgb.kjwl.view.ui.adapter.self.publish.PackersTypeChoiceAdapter;
import com.sgb.kjwl.viewmodel.self.publish.PackersTypeModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.MaxRecyclerView;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class PackersTypeChooicetActivity extends AppActivity {
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;
    private ActivityPackersTypeChooiceBinding binding;
    private CategoryEntity categoryEntity;
    private List<PackersTypeChoiceAdapter> packersTypeChoiceAdapterList;
    private List<String[]> lists;
    private List<CategoryEntity<CategoryEntity>> data;
    @Inject
    PackersTypeModel viewModel;

    private List<String[]> categoryList;
    private String title = "";

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, PackersTypeChooicetActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(PackersTypeChooicetActivity.this, R.layout.activity_packers_type_chooice);
        binding.backView.setOnClickListener(this);
        binding.okView.setOnClickListener(this);
    }

    @Override
    protected void init() {
        packersTypeChoiceAdapterList = new ArrayList<>();
        lists = new ArrayList<>();
        viewModel.getCategoryModel();
    }

    public void showCategoryView(List<CategoryEntity<CategoryEntity>> data) {
        this.data = data;
        for (int i = 0; i < data.size(); i++) {
            PackersTypeChoiceAdapter adapter = new PackersTypeChoiceAdapter(this, null);
            packersTypeChoiceAdapterList.add(adapter);
            categoryEntity = data.get(i);
            if (categoryEntity.getDatas().size() != 0) {
                addRecyclerView(adapter, categoryEntity.getDatas(), i, categoryEntity.getName(), categoryEntity);
            }

        }
    }

    private void addRecyclerView(PackersTypeChoiceAdapter adapter, List<CategoryEntity> children, final int i, String title, CategoryEntity categoryEntity) {
        //List
        LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        adapter.setMultiSelect(true);
        adapter.setDefItem(-1);
        MaxRecyclerView recyclerView = new MaxRecyclerView(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setAdapter(adapter);
        recyclerView.setNestedScrollingEnabled(false);
        adapter.setDatas(children);
        layoutParams2.setMargins(((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics())), 0, 0, 0);
        adapter.setOnItemClick(new AdapterOnItemClick<CategoryEntity>() {
            @Override
            public void onItemClick(CategoryEntity filterEntity, int position) {
                MLog.d("test", "child " + filterEntity.getName());

            }
        });

        //checkbox和标题
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER_VERTICAL;
        LinearLayout relativeLayout = new LinearLayout(this);
        relativeLayout.setPadding(((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics())), ((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics())), ((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics())), ((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics())));
        CheckBox checkBox = new CheckBox(this);
        checkBox.setButtonDrawable(getResources().getDrawable(R.drawable.check_bg));
        TextView textView = new TextView(this);
        textView.setText(title);
        textView.setTextSize(14);
        textView.setTextColor(getResources().getColor(R.color.color_B6B6B6));
        textView.setPadding(((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics())), 0, 0, 0);
        relativeLayout.addView(checkBox);
        relativeLayout.addView(textView);
        ArrayList<CategoryEntity> list;
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    adapter.checkALLDatas();
                } else {
                    adapter.resetCheckDatas();
                }
            }
        });
        binding.parentLl.addView(relativeLayout, layoutParams);
        binding.parentLl.addView(recyclerView, layoutParams2);

        if (categoryList == null) {
            return;
        }
        for (String[] number : categoryList) {
            if (categoryEntity != null && number != null && number.length > 1) {
                if (categoryEntity.getNo().equals(number[0])) {
                    for (int j = 0; j < children.size(); j++) {
                        if (children.get(j).getNo().equals(number[1])) {
                            adapter.setCheckDefault(j);
                        }
                    }
                }
            }
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ok_view:
                /*if (packersTypeChoiceAdapterList.size() != 0) {
                    for (int i = 0; i < packersTypeChoiceAdapterList.size(); i++) {
                        if (packersTypeChoiceAdapterList.get(i).getCheckDatas().size() != 0) {
                            String[] noArry = new String[packersTypeChoiceAdapterList.get(i).getCheckDatas().size()];
                            for (int j = 0; j < packersTypeChoiceAdapterList.get(i).getCheckDatas().size(); j++) {
                                noArry[j] = packersTypeChoiceAdapterList.get(i).getCheckDatas().get(j).getNo();
                            }
                            lists.add(noArry);
                        }

                    }
                }*/
                mHandler.sendEmptyMessage(MSG_LOAD_DATA);
                break;
            case R.id.back_view:
                finish();
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    EventBus.getDefault().post(PackersPublishEvent.make().setMessageTag(EventConstant.EVENT_PICK_TYPE).setMessageData(lists));
                    EventBus.getDefault().post(PackersPublishEvent.make().setMessageTag(EventConstant.EVENT_PICK_TYPE_TITLE).setMessageData(title));
                    finish();
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initData() {
        lists.clear();
        StringBuffer sb = new StringBuffer();
        if (packersTypeChoiceAdapterList.size() != 0) {
            for (int i = 0; i < packersTypeChoiceAdapterList.size(); i++) {
                if (packersTypeChoiceAdapterList.get(i).getCheckDatas().size() != 0) {
//                            String[] noArry = new String[2];
                    for (int j = 0; j < packersTypeChoiceAdapterList.get(i).getCheckDatas().size(); j++) {
                        if (!sb.toString().contains(data.get(i).getName())) {
                            sb.append(data.get(i).getName());
                        }
                        String[] noArry = new String[2];
                        noArry[0] = data.get(i).getNo();
                        noArry[1] = packersTypeChoiceAdapterList.get(i).getCheckDatas().get(j).getNo();
                        lists.add(noArry);
                    }

                }

            }
        }
        title = sb.toString();
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(PackersPublishEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_PICK_DEFAULT) {
            categoryList = (List<String[]>) event.getMessageData();
            EventBus.getDefault().removeStickyEvent(event);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}

